import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../HomePage.dart';

// void main() => runApp(
//   MultiProvider(
//     providers: [
//       ChangeNotifierProvider(create: (_) => PageAState()),
//       ChangeNotifierProvider(create: (_) => PageBState()),
//       ChangeNotifierProvider(create: (_) => PageCState()),
//     ],
//     child: MyApp2(),
//   ),
// );


class MyApp2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '状态保持示例',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomeScreen(),
    );
  }
}

// 主页面框架
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _currentIndex = 0;
  final List<Widget> _pages = [
    HomePage(),
    PageB(),
    PageC(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: _pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) => setState(() => _currentIndex = index),
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '页面A',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: '页面B',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: '页面C',
          ),
        ],
      ),
    );
  }
}

// 页面A的状态管理
class PageAState with ChangeNotifier {
  int _selectIndex = 0;

  int get selectIndex => _selectIndex;

  set selectIndex(int value) {
    _selectIndex = value;
    notifyListeners();
  }

  int _page = 1; // 新增页码
  bool _hasMore = true; // 是否还有更多数据
  bool _isLoadingMore = false; // 是否正在加载更多

  bool get hasMore => _hasMore;

  bool get isLoadingMore => _isLoadingMore;

  bool _isLoading = false;
  bool _hasError = false;

  bool get isLoading => _isLoading;

  set isLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  bool get hasError => _hasError;

  int _counter = 0;

  int get counter => _counter;

  void increment() {
    _counter++;
    notifyListeners();
  }

  List<TestBean> _listBeans = [];

  List<TestBean> get listBeans => _listBeans;

  void addListBeans(List<TestBean> list) {
    _listBeans.addAll(list);
    notifyListeners();
  }

  Future<void> loadData({bool isRefresh = false}) async {
    try {
      _isLoading = true;
      _hasError = false;

      // 模拟网络请求延迟
      await Future.delayed(Duration(seconds: 2));
      // 模拟添加数据
      var list = List.generate(
          20,
          (index) => TestBean("android开发$index", "${index + 10} K",
              "科技有限公司 未融资 100-1000人", ["5-10年", "本科", "SDK", "Android"]));
      _listBeans.addAll(list);
      print("get data ${_listBeans.length} ${listBeans.length}");
    } catch (e) {
      _hasError = true;
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }

  Future<void> loadMore() async {
    try {
      if (!_isLoading) {
        print("start get more");
        loadData();
        print("get data ${_listBeans.length} ${listBeans.length}");
      }
    } catch (e) {
    } finally {
      notifyListeners();
    }
  }

  // 下拉刷新
  Future<void> onRefresh() async {
    _listBeans.clear();
    await loadData();
  }
}

// 页面A
class PageA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final state = Provider.of<PageAState>(context);

    var selectIndex = 0;
    List<TestBean> listBeans = [];
    bool _loading = false;
    int _page = 1;
    final ScrollController _scrollController = ScrollController();

    // 初始加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (state.listBeans.isEmpty && !state.isLoading) {
        state.loadData();
      }
    });

    return Scaffold(
      appBar: AppBar(title: Text('页面A')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('计数器值：${state.counter}'),
            ElevatedButton(
              onPressed: state.increment,
              child: Text('增加'),
            ),
          ],
        ),
      ),
    );
  }
}

// 页面B的状态管理
class PageBState with ChangeNotifier {
  String _text = '初始文本';

  String get text => _text;

  void updateText(String newText) {
    _text = newText;
    notifyListeners();
  }
}

// 页面B
class PageB extends StatelessWidget {
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final state = Provider.of<PageBState>(context);

    return Scaffold(
      appBar: AppBar(title: Text('页面B')),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            Text('当前文本：${state.text}'),
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                labelText: '输入新文本',
                suffixIcon: IconButton(
                  icon: Icon(Icons.send),
                  onPressed: () {
                    state.updateText(_controller.text);
                    _controller.clear();
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 页面C
class PageC extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('页面C')),
      body: Center(
        child: Text('简单静态页面', style: TextStyle(fontSize: 24)),
      ),
    );
  }
}

// 页面C的状态管理（演示用，实际未使用）
class PageCState with ChangeNotifier {}
